﻿#include "NewTcpClient.h"
#include "GlobalManager.h"
#include <QImage>
#include <QFile>
#include <QDir>

NewTcpClient::NewTcpClient() {

}

NewTcpClient::~NewTcpClient(){
    if(transferProxy) {
        delete  transferProxy;
    }
}

void NewTcpClient::setClientSocket(QTcpSocket *ptr)
{
    mClientSocket = ptr;
    connect(mClientSocket, &QTcpSocket::readyRead, this, &NewTcpClient::readyReadySlot);
    connect(mClientSocket, &QTcpSocket::disconnected, this, &NewTcpClient::disconnectSlot);
    set_transferProxy(new TransferProxy(ptr));
    transferProxy->setSendName("You");
    mIsConnectFlag = true;
}

void NewTcpClient::sendMessageTClient(const QString &info, bool isDsplayText)
{
    transferProxy->sendInfo("NormalChat", info, isDsplayText);
}

void NewTcpClient::readyReadySlot() {
    TransferBase* basePtr = transferProxy->isHaveReceiving();
    qDebug() << "basePtr = " <<basePtr;
    //是否有任务在运行中，如果有 就直接去运行的
    if(basePtr) {
        transferProxy->recvInfo("");
    }else {
        //一行是以\n位结尾的 读一行数据
        QString message = mClientSocket->readLine();
    //        message = message.remove("\n");
        qDebug() << "read message = " << message << "this ptr = " << this;
        if(message.contains("login@:")) {
            validateLogon(message.remove("login@:"));
        }else if(message.contains("register@:")) {
            registerAccount(message.remove("register@:"));
        }else {
            qDebug() << "232";
            transferProxy->recvInfo(message);
        }
    }
}

void NewTcpClient::disconnectSlot()
{
    qDebug() << "disconnect";
    //退出的时候把连接状态改成0
    ClientDataRecordSqlTableModel* infoModel = GlobalManager::GetInstance()->get_clientDataRecordSqlTableModel();
    int index = 0;
    infoModel->accountIsInModel(mAccount, index);
    infoModel->modifyData(index, ClientDataRecordSqlTableModel::UserState, "0");
    mIsConnectFlag = false;
}

void NewTcpClient::validateLogon(const QString &str)
{
    //login@:account:%1;password:%2
    QStringList strList = str.split(";");
    if(strList.size() == 2) {
        QStringList accountList = strList.at(0).split(":");
        QStringList passwordList = strList.at(1).split(":");
        if(accountList.size() == 2 && passwordList.size() == 2) {
            ClientDataRecordSqlTableModel* infoModel = GlobalManager::GetInstance()->get_clientDataRecordSqlTableModel();
            int count = GlobalManager::GetInstance()->get_clientDataRecordSqlTableModel()->rowCount();
            for(int i = 0; i < count; i++) {
                QString modelAccount = infoModel->getData(i, (int)ClientDataRecordSqlTableModel::AccountNumber).toString();
                QString password = infoModel->getData(i, (int)ClientDataRecordSqlTableModel::Password).toString();
                int errorTimes = infoModel->getData(i, (int)ClientDataRecordSqlTableModel::ErrorTimes).toUInt();
                //账号相等
                if(modelAccount == accountList.at(1)) {
                    if(errorTimes >= 3) {
                        sendreply("login", PasswordFailedMoreThanTimes, "Password failed more than 3 times");
                        return;
                    }
                    if(passwordList.at(1) == password) {
                        sendreply("login", LoginSucceeded, "login succeeded!!");
                        mAccount = modelAccount;
                        //清空错误次数 设置当前状态为连接
                        infoModel->modifyData(i, (int)ClientDataRecordSqlTableModel::ErrorTimes, "0");
                        infoModel->modifyData(i, (int)ClientDataRecordSqlTableModel::UserState, "1");
                        transferProxy->setReceiveName(mAccount);
                    }else {
                        //密码错误
                        sendreply("login", PasswordError, "password error!");
                        QString mdiyR = QString("%1").arg(errorTimes+1);
                        qDebug()<<"modir = "<<mdiyR;
                        infoModel->modifyData(i,(int)ClientDataRecordSqlTableModel::ErrorTimes,mdiyR);
                    }
                    return;
                }
            }
            sendreply("login", AccountNotExist, "account not exist!");
            return;
        }
    }
    sendreply("login", UnKonwError,"Unkonw Error!");

    return;
}

void NewTcpClient::sendreply(QString head, int code, QString info)
{
    mClientSocket->write(QString("%1@:code:%2;info:%3").arg(head).arg(code).arg(info).toStdString().c_str());
}

void NewTcpClient::registerAccount(const QString &str)
{
    QStringList strList = str.split(";");
    if(strList.size() == 2) {
        QStringList accountList = strList.at(0).split(":");
        QStringList passwordList = strList.at(1).split(":");
        if(accountList.size() == 2 && passwordList.size() == 2) {
            ClientDataRecordSqlTableModel* infoModel = GlobalManager::GetInstance()->get_clientDataRecordSqlTableModel();
            QString account = accountList.at(1);
            QString password = passwordList.at(1);
            int index = 0;
            bool res = infoModel->accountIsInModel(account, index);
            if(res) {
                sendreply("register", RegisterAccountExist,"account aready exist!");
            }else {
                infoModel->insertAccount(account, password);
                sendreply("register", RegisterAccountSucceeded, "regiter account succeeded!");
            }
            return;
        }
    }
    return;
}


void NewTcpClient::updataComInfo(QString message)
{
    QString time = QDateTime::currentDateTime().toString ("yyyy-MM-dd hh:mm:ss");
    comInfo = QString("%1\nUser@%2 SendMessage %3:\n%4").arg(comInfo).arg(mAccount).arg(time).arg(message);
    //因为QML显示的是HTML 所以要把\n换成br
    comInfo = comInfo.replace("\n","<br>");
    emit comInfo_Notify();
}

//void NewTcpClient ::sendMovie(QString path) {
//    qDebug() << "sendImage = " << path;
//    mNetPtr->sendImage2Client(path,"Movie");
//    //<img src="本地图片地址" alt="文本说明" width="42" height="42">
//    //imagSrc是HTML的一段代码，根据这个可以显示图片
//    //QString imagSrc = QString("<img src = \"%1\" width=\"%2\" height=\"%3\"><br>").arg(path).arg(400).arg(400);
//    //qDebug() << "im str1 = " << imagSrc;
//    //"<a href=\"file:///D:/BaiduNetdiskDownload/QT/XM/build-TopCom2-Desktop_Qt_5_14_2_MSVC2017_64bit-Release/Server/24-总结0.avi\">张玮媛大战郭勋.mp4<br></a>"
//    //zwy0.avi
//    QString fileName = QFileInfo(path).fileName();
////    QFileInfo info(path);
////    QString fileName = info.fileName();
//    QString moveLink= QString("<a href=\"%1\">%2\n</a>").arg(path).arg(fileName);
//    qDebug() << "imagSrc = " << moveLink;
//    updataComInfo(moveLink);
//}

void NewTcpClient::disconnectServer()
{
    mClientSocket->disconnectFromHost();
}

